﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Microsoft.SharePoint.Taxonomy;
using Microsoft.SharePoint;
using System.Xml;
using System.Globalization;
using System.Management.Automation;
using Microsoft.SharePoint.Publishing;

namespace SharePoint.Utilities.Cmdlets
{
    public static class UpdateTaxonomyFieldsHelper
    {

        public static string siteCollectionUrl;

        public static void UpdateTaxonomyFields()
        {
            using (SPSite site = new SPSite(siteCollectionUrl))
            {
                PublishingSite pubsite = new PublishingSite(site);
                TaxonomySession txnSession = new TaxonomySession(site);
                ShowMessage("Retrieving Taxonomy Session");

                foreach (SPWeb web in site.RootWeb.Webs)
                {
                    //SPWeb web = site.RootWeb.Webs[1];
                    PublishingWeb pubweb = PublishingWeb.GetPublishingWeb(web);

                    ShowMessage(string.Format("Retrieving Publishing Web : {0}", web.Title));
                    SPQuery query = new SPQuery();
                    query.ViewAttributes = "Scope=\"RecursiveAll\"";
                    PublishingPageCollection pageslib;

                    try
                    {
                        pageslib = pubweb.GetPublishingPages(query);
                    }
                    catch (Exception ex)
                    {

                        ShowMessage(ex.Message);
                        continue;
                    }

                    foreach (PublishingPage page in pageslib)
                    {

                        try
                        {
                            ShowMessage(string.Format("Updating Page : {0}", page.Title));
                            if (page.ListItem.FileSystemObjectType == SPFileSystemObjectType.File)
                            {
                                if (page.ListItem.File.CheckOutType == SPFile.SPCheckOutType.Online)
                                {
                                    try
                                    {
                                        page.ListItem.File.CheckIn("check in");
                                        page.ListItem.File.CheckOut();

                                    }
                                    catch (Exception ex)
                                    {


                                    }
                                }
                                if (page.ListItem.File.CheckOutType == SPFile.SPCheckOutType.None)
                                {
                                    page.CheckOut();

                                }
                                else
                                {
                                    try
                                    {
                                        page.ListItem.File.UndoCheckOut();
                                        page.CheckOut();
                                    }
                                    catch (Exception ex)
                                    {


                                    }

                                }

                                foreach (SPField field in page.ListItem.Fields)
                                {


                                    if (field.GetType().Name == "TaxonomyField")
                                    {
                                        ShowMessage(string.Format("Updating Field : {0}", field.Title));
                                        TaxonomyField taxfield = (TaxonomyField)field;


                                        string currentvalue = (string)page.ListItem.Properties[taxfield.Title];
                                        var templatefield = (TaxonomyField)page.ListItem.ParentList.ParentWeb.Site.RootWeb.Fields[field.Title];
                                        var defaultvalue = templatefield.DefaultValue;

                                        var termstore = txnSession.TermStores[templatefield.SspId];
                                        var termset = termstore.GetTermSet(templatefield.TermSetId);


                                        taxfield.SspId = templatefield.SspId;
                                        taxfield.Update();


                                        taxfield.TermSetId = templatefield.TermSetId;
                                        taxfield.Update();



                                        TaxonomyFieldValue taxValue = page.ListItem[field.Title] as TaxonomyFieldValue;
                                        if (taxValue != null)
                                            taxfield.SetFieldValue(page.ListItem, taxValue);


                                        page.ListItem.Update();

                                    }
                                }


                                page.ListItem.Update();

                                try
                                {

                                    page.CheckIn("code check in complete");

                                }
                                catch (Exception ex)
                                {


                                }

                            }
                        }
                        catch (Exception ex)
                        {

                            ShowMessage(ex.ToString());
                        }






                    }

                }
            }


        }

        /// <summary>
        /// Updates taxonomy fields with the SSPId of the term store sent.
        /// This script needs to be run locally on teh servier
        /// There is no other way to get SSPId other than from taxonomy session.
        /// This command needs to be run after running Import-SiteSolumns, to associate taxonomy fields to right term store.
        /// </summary>
        /// <param name="siteUrl"></param>
        /// <param name="termStoreName"></param>
        public static string UpdateTaxonomyFieldsWithSspId(string siteUrl, string termStoreName)
        {
            string infoMessages = string.Empty;
            SPSite siteCollection;
            TermStore termStore;
            using (siteCollection = new SPSite(siteUrl))
            {
                // Get taxonomy session
                TaxonomySession txnSession = new TaxonomySession(siteCollection);
                termStore = txnSession.TermStores[termStoreName];
                // Loop through all site columns
                for (int i = 0; i <= siteCollection.RootWeb.Fields.Count - 1; i++)
                {
                    SPField field = siteCollection.RootWeb.Fields[i];
                    // check if it is a metadata field
                    if (field.GetType().Name == "TaxonomyField")
                    {
                        TaxonomyField taxField = (TaxonomyField)field;
                        // check whether the field belongs to term store sent
                        if (termStore.GetTermSet(taxField.TermSetId) != null)
                        {
                            taxField.SspId = termStore.Id;
                            taxField.Update();
                            ShowMessage(taxField.Title);
                            infoMessages += taxField.Title + " <br/>";
                        }
                    }
                }
            }
            return infoMessages;

        }


        public static void ShowMessage(string Message)
        {
            Console.WriteLine(DateTime.Now.ToString() + ":" + Message);
        }
    }
}
